import random
import urllib.request
import urllib.parse
import urllib
import re

import time
from lxml import etree


def doGetCodeAndPrice(url):
    # index=url.find('?')
    # url=url[0:index]
    # print(url)

    str=url.split('/')
    code=str[len(str)-1]
    price=doGetPrice(url)


    return code,price



def doGetPrice(url):
    if (url == None or len(url) == 0):
        return None
    Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
    req = urllib.request.Request(url)

    req.add_header('Accept',Accept)
    req.add_header('Connection','keep-alive')
    req.add_header('Content-Encoding','gzip')
    req.add_header('Content-Type','text/html; charset=UTF-8')


    try:
        response = urllib.request.urlopen(req, timeout=5)
        thePage = response.read()
        thePage = thePage.decode("UTF-8", 'ignore')

        tree = etree.HTML(str(thePage))
        body = str(tree.xpath('//*[@class="dpOurPrice"]/text()'))
        body=body.replace(",", "")
        res_tr = r'￥([-+]?[0-9]*\.?[0-9]+)'
        p_tr = re.findall(res_tr, body)

        return float(p_tr[0])
    except Exception as e:
     print(e)

def getCodeAndPrice(url):
    count=0
    while (1):
        t = doGetCodeAndPrice(url)
        time.sleep(1)
        count=count+1
        if (count>=5 or t[1]!=None):
            break
    return t

def getPrice(url):
    count=0
    price=None
    while (1):
        price = doGetPrice(url)
        time.sleep(1)
        count=count+1
        if (count>=5 or price!=None):
            break
    return price

print(getCodeAndPrice('https://www.amazon.cn/gp/aw/d/B0186FESGW'))